package org.example.network.demo3;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Gong.Yang
 */
public class ReactorDemo {
    public static void main(String[] args) throws IOException {
        new BoosEventLoop().start(8888);
    }

    @Slf4j
    static class BoosEventLoop implements Runnable {
        private Selector boss;
        private boolean start;
        private WorkerEventLoop[] workers;
        AtomicInteger index = new AtomicInteger();

        public void start(int port) throws IOException {
            if (!start) {
                ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
                serverSocketChannel.bind(new InetSocketAddress(port));
                serverSocketChannel.configureBlocking(false);
                boss = Selector.open();
                SelectionKey key = serverSocketChannel.register(boss, 0, null);
                key.interestOps(SelectionKey.OP_ACCEPT);
                workers = initWorkers(Runtime.getRuntime().availableProcessors() * 2);//两倍核心数的worker
                new Thread(this, "boss").start();
                log.debug("boss start...");
                start = true;
            }
        }

        private WorkerEventLoop[] initWorkers(int worker) {
            if (worker <= 0) worker = 1;
            WorkerEventLoop[] workers = new WorkerEventLoop[worker];
            for (int i = 0; i < worker; i++) {
                workers[i] = new WorkerEventLoop(i);
            }
            return workers;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    boss.select();
                    Iterator<SelectionKey> keys = boss.selectedKeys().iterator();
                    while (keys.hasNext()) {
                        SelectionKey key = keys.next();
                        keys.remove();
                        if (key.isAcceptable()) {
                            ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
                            SocketChannel channel = serverChannel.accept();
                            channel.configureBlocking(false);
                            workers[workers.length % index.getAndIncrement()].regist(channel);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        }
    }

    @Slf4j
    static class WorkerEventLoop implements Runnable {
        private int index;
        private Selector worker;
        private boolean start;
        private ConcurrentLinkedQueue<Runnable> registerTask = new ConcurrentLinkedQueue<>();

        public WorkerEventLoop(int index) {
            this.index = index;
        }

        public void regist(SelectableChannel channel) throws IOException {
            if (!start) {
                worker = Selector.open();
                new Thread(this, "worker - " + index).start();
                start = true;
            }

            registerTask.add(() -> {
                try {
                    SelectionKey key = channel.register(worker, 0, null);
                    key.interestOps(SelectionKey.OP_READ);
                    worker.selectNow();     //注册过程中可能有其他事件发生 ， 将这些事件放入Set《Key》中
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

            worker.wakeup();
        }

        @Override
        public void run() {
            while (true) {
                try {
                    worker.select();
                    Runnable task = registerTask.poll();
                    if (Objects.nonNull(task)) {
                        task.run();
                    }
                    Set<SelectionKey> keys = worker.selectedKeys();
                    Iterator<SelectionKey> iterator = keys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if (key.isReadable()) {
                            SocketChannel channel = (SocketChannel) key.channel();
                            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);
                            try {
                                int read = channel.read(byteBuffer);
                                if (read == -1) {
                                    key.cancel();
                                    channel.close();
                                } else {
                                    String content = StandardCharsets.UTF_8.decode(byteBuffer).toString();
                                    log.info("{}:{}", channel.getRemoteAddress(), content);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                key.cancel();
                                channel.close();
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
